package com.wuyoucar.service.impl;

import com.wuyoucar.common.ResultBean;
import com.wuyoucar.entity.TUser;
import com.wuyoucar.entity.TUserinfo;
import com.wuyoucar.mapper.TUserInfoMapper;
import com.wuyoucar.mapper.TUserMapper;
import com.wuyoucar.service.InMailservice;
import com.wuyoucar.util.mailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author: jiangdz
 * @ProjectName: mywuyou_car
 * @Package: com.wuyoucar.service.imp
 * @ClassName: MailServiceImpl
 * @Description:
 * @Date: 2020-09-23  16:42
 * @UpdateUser: asus
 * @UpdateDate: 2020-09-23  16:42
 * @UpdateRemark: [说明本次修改内容]
 * @Version: [v1.0]
 * @Since JDK 1.8
 */
@Service
public class MailServiceImpl implements InMailservice {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    TUserInfoMapper tUserInfoMapper;

    //获取验证码
    @Override
    public ResultBean getCode(String to) {
        ResultBean resultBean = new ResultBean();
        String code = mailUtils.sendMessage(to);
        redisTemplate.opsForValue().set("code", code, 5, TimeUnit.MINUTES);
        if (code != null) {
            resultBean.setMsg("验证码获取成功！");
            resultBean.setCode(0);
            resultBean.setData(code);
        } else {
            resultBean.setMsg("验证码获取失败！");
            resultBean.setCode(-1);
        }
        return resultBean;
    }

    //绑定邮箱
    @Override
    public ResultBean udateMail(String to, String code, int userid) {
        ResultBean resultBean = new ResultBean();
        String myCode = redisTemplate.opsForValue().get("code");
        if (myCode.equals(code)) {
            TUserinfo tUserinfo = new TUserinfo();
            tUserinfo.setUserid(userid);
            tUserinfo.setEmail(to);
            int n = tUserInfoMapper.updateTUserInfoById(tUserinfo);
            if (n != 0) {
                resultBean.setMsg("绑定成功！");
                resultBean.setCode(0);
            } else {
                resultBean.setMsg("绑定失败！");
                resultBean.setCode(101);
            }
        } else {
            resultBean.setCode(304);
            resultBean.setMsg("验证码错误");
        }
        return resultBean;
    }

    @Override
    public TUserinfo selectUserinfoByuserid(Integer userid) {
        TUserinfo tUserinfo = tUserInfoMapper.selectUserinfoByuserid(userid);
        return tUserinfo;


    }

    //理赔次数加1
    @Override
    public ResultBean addPaytime(Integer userid, Integer paytime) {
        Integer paytimes = selectUserinfoByuserid(userid).getPaytimes();
        Integer paytimes1 = paytimes + paytime;
        int i = tUserInfoMapper.addPaytime(new TUserinfo(userid, paytimes1));
        if (i > 0) {
            return new ResultBean(200, "增加成功");
        } else {
            return new ResultBean(404, "增加失败");
        }
    }

}
